<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import type { ArticleVO, CategoryVO } from '@/types'
import { articleApi } from '@/api/article'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/store/modules/auth'

const authStore = useAuthStore()
const articles = ref<ArticleVO[]>([])
const categories = ref<CategoryVO[]>([])
const selectedCategory = ref<number>(0)
const currentPage = ref(1)
const pageSize = ref(10)
const loading = ref(false)
const error = ref('')
const total = ref(0)
const totalPage = ref(0)
const noMore = ref(false)
const categoryLoading = ref(false)
const categoryError = ref(false)
const router = useRouter()

// 加载分类列表
const loadCategories = async () => {
  categoryLoading.value = true
  categoryError.value = false

  try {
    console.log('开始加载分类列表...')
    const categories_data = await articleApi.getCategories()
    if (categories_data.code === 200) {
      if (Array.isArray(categories_data.data)) {
        categories.value = categories_data.data
        console.log('设置后的分类列表:', categories.value)
      } else {
        console.error('分类数据格式不正确')
        categories.value = []
      }
    } else {
      console.error('获取分类列表失败:', categories_data.msg)
      categoryError.value = true
      categories.value = []
    }
  } catch (err) {
    console.error('获取分类列表失败:', err)
    categoryError.value = true
    categories.value = []
  } finally {
    categoryLoading.value = false
  }
}

// 切换分类
const handleCategoryChange = (categoryId: number) => {
  selectedCategory.value = categoryId
  articles.value = []
  currentPage.value = 1
  noMore.value = false
  loadArticles()
}

// 监听滚动加载
const handleScroll = async () => {
  if (loading.value || noMore.value) return

  const scrollHeight = document.documentElement.scrollHeight
  const scrollTop = document.documentElement.scrollTop
  const clientHeight = document.documentElement.clientHeight

  if (scrollHeight - scrollTop - clientHeight < 100) {
    await loadArticles()
  }
}

// 加载文章列表
const loadArticles = async () => {
  if (loading.value || noMore.value) return

  loading.value = true
  error.value = ''

  try {
    const pageData = await articleApi.getArticles({
      current: currentPage.value,
      pageSize: pageSize.value,
      categoryId: selectedCategory.value,
    })

    if (pageData.code === 200) {
      articles.value = [...articles.value, ...(pageData.data.data || [])]
      total.value = pageData.data.total
      totalPage.value = pageData.data.totalPage

      if (currentPage.value >= totalPage.value) {
        noMore.value = true
      } else {
        currentPage.value++
      }
    } else {
      error.value = pageData.msg
    }
  } catch (err: any) {
    error.value = '获取文章列表失败'
    console.error('获取文章列表详细错误:', err)
  } finally {
    loading.value = false
  }
}

// 点赞文章
const handleLike = async (articleId: number) => {
  try {
    await articleApi.setLike(articleId, 1)
    const article = articles.value.find((a) => a.id === articleId)
    if (article) {
      article.isLiked = 1
      article.liked++
    }
  } catch (err) {
    console.error('点赞失败:', err)
  }
}

// 添加跳转到文章详情的方法
const goToArticleDetail = (articleId: number) => {
  router.push(`/article/${articleId}`)
}

onMounted(() => {
  loadCategories()
  loadArticles()
  window.addEventListener('scroll', handleScroll)
})

onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll)
})
</script>

<template>
  <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <!-- 头部区域 -->
    <div class="mb-8">
      <h2 class="text-3xl font-bold text-gray-900 mb-6">
        文章列表
        <span class="text-lg font-normal text-gray-500">(共 {{ total }} 篇)</span>
      </h2>

      <!-- 分类选择器 -->
      <div class="bg-white p-4 rounded-lg shadow-sm">
        <div class="flex flex-wrap gap-3">
          <button
            @click="handleCategoryChange(0)"
            :class="[
              'px-4 py-2 rounded-full text-sm font-medium transition-colors',
              selectedCategory === 0
                ? 'bg-blue-600 text-white shadow-sm'
                : 'bg-gray-100 text-gray-700 hover:bg-gray-200',
            ]"
          >
            全部文章
          </button>
          <template v-if="!categoryLoading && !categoryError && categories.length > 0">
            <button
              v-for="category in categories"
              :key="category.id"
              @click="handleCategoryChange(category.id)"
              :class="[
                'px-4 py-2 rounded-full text-sm font-medium transition-colors',
                selectedCategory === category.id
                  ? 'bg-blue-600 text-white shadow-sm'
                  : 'bg-gray-100 text-gray-700 hover:bg-gray-200',
              ]"
            >
              {{ category.categoryName }}
            </button>
          </template>
        </div>
      </div>
    </div>

    <!-- 空态页面 -->
    <div
      v-if="!loading && (error || articles.length === 0)"
      class="bg-white rounded-lg shadow-sm p-12"
    >
      <div class="flex flex-col items-center">
        <div class="w-32 h-32 mb-6 text-gray-300">
          <svg class="w-full h-full" viewBox="0 0 24 24" fill="none" stroke="currentColor">
            <path
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="1"
              d="M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z"
            />
          </svg>
        </div>
        <h3 class="text-xl font-medium text-gray-900 mb-2">
          {{ error ? '获取文章失败' : '暂无文章' }}
        </h3>
        <p class="text-gray-500 text-center max-w-md mb-6">
          {{
            error
              ? '抱歉，获取文章列表时出现了问题，请稍后再试'
              : selectedCategory === 0
                ? '目前还没有任何文章，敬请期待'
                : '当前分类下暂无文章'
          }}
        </p>
        <button
          v-if="error || selectedCategory !== 0"
          @click="handleCategoryChange(0)"
          class="px-6 py-2 bg-blue-600 text-white rounded-full hover:bg-blue-700 transition-colors shadow-sm"
        >
          {{ error ? '重试' : '查看全部文章' }}
        </button>
      </div>
    </div>

    <!-- 文章列表 -->
    <div
      v-else-if="articles.length > 0"
      class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6"
    >
      <div
        v-for="article in articles"
        :key="article.id"
        class="bg-white rounded-lg shadow-sm hover:shadow-md transition-all duration-300 overflow-hidden group cursor-pointer"
        @click="goToArticleDetail(article.id)"
      >
        <div class="aspect-video overflow-hidden">
          <img
            :src="article.articleCover || '/default-cover.png'"
            :alt="article.articleTitle"
            class="w-full h-full object-cover transform group-hover:scale-105 transition-transform duration-300"
            @error="
              (e: Event) => {
                const target = e.target as HTMLImageElement
                if (target) target.src = '/default-cover.png'
              }
            "
          />
        </div>

        <div class="p-6">
          <h3 class="text-lg font-semibold text-gray-900 line-clamp-1 mb-2">
            {{ article.articleTitle }}
          </h3>
          <p class="text-gray-600 text-sm line-clamp-2 mb-4">
            {{ article.articleIntroduction }}
          </p>

          <div class="flex items-center justify-between text-sm text-gray-500">
            <div class="flex items-center space-x-4">
              <span class="flex items-center">
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  class="h-4 w-4 mr-1"
                  viewBox="0 0 20 20"
                  fill="currentColor"
                >
                  <path
                    d="M2 10.5a1.5 1.5 0 113 0v6a1.5 1.5 0 01-3 0v-6zM6 10.333v5.43a2 2 0 001.106 1.79l.05.025A4 4 0 008.943 18h5.416a2 2 0 001.962-1.608l1.2-6A2 2 0 0015.56 8H12V4a2 2 0 00-2-2 1 1 0 00-1 1v.667a4 4 0 01-.8 2.4L6.8 7.933a4 4 0 00-.8 2.4z"
                  />
                </svg>
                {{ article.liked }}
              </span>
              <span class="flex items-center">
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  class="h-4 w-4 mr-1"
                  viewBox="0 0 20 20"
                  fill="currentColor"
                >
                  <path
                    fill-rule="evenodd"
                    d="M10 18a8 8 0 100-16 8 8 0 000 16zm1-12a1 1 0 10-2 0v4a1 1 0 00.293.707l2.828 2.829a1 1 0 101.415-1.415L11 9.586V6z"
                    clip-rule="evenodd"
                  />
                </svg>
                <time class="truncate max-w-[120px]">{{ article.createTime }}</time>
              </span>
            </div>

            <button
              v-if="article.isLiked === 0 && authStore.user"
              @click.stop="handleLike(article.id)"
              class="inline-flex items-center px-3 py-1.5 rounded-full text-sm font-medium text-blue-600 bg-blue-50 hover:bg-blue-100 transition-colors"
            >
              点赞
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="flex items-center justify-center py-8 text-gray-600">
      <div
        class="animate-spin rounded-full h-8 w-8 border-2 border-blue-600 border-t-transparent"
      ></div>
    </div>

    <!-- 加载完成提示 -->
    <div v-if="noMore && articles.length > 0" class="text-center py-6 text-gray-500 text-sm">
      没有更多文章了
    </div>
  </div>
</template>

<style scoped>
.article-card {
  display: flex;
  flex-direction: column;
  height: 100%;
}

/* 添加图片悬停效果 */
.group:hover img {
  transform: scale(1.05);
}

/* 添加平滑过渡效果 */
img {
  transition: transform 0.3s ease-in-out;
}
</style>
